import type { LearnBaseQuestionInfo } from '@/api/base/types'
import type { ExamRule, ExamResult, ExamResultQuestion } from '@/api/exam/types'
import { ExamTypeEnum, QuestionOptionTypeEnum } from '@/api/constants'
import { useLearnBaseInfoStore } from '@/stores/modules/learn_base_info'
import { useMockExamStore } from '@/stores/modules/mock_exam_store'
import { useLocateClassesCode } from './LearnBase'

export const useExamRule = (baseType: string) => {

  let locateClassesCode = useLocateClassesCode(baseType)
  const learnBaseInfoStore = useLearnBaseInfoStore()
  const mockExamStore = useMockExamStore()

  let isHaveLocateQuestions = false
  if (locateClassesCode) {
    isHaveLocateQuestions = true
  }

  let examReason = learnBaseInfoStore.learnBaseInfo.examReason
  let driveType = learnBaseInfoStore.learnBaseInfo.driveType
  let examRule = mockExamStore.examRules.find(item => item.examReason == examReason && item.driveType == driveType && item.baseType == baseType
    && item.isHaveLocateQuestins == isHaveLocateQuestions
  )


  // 更新本市考题类别代码代码
  if (examRule) {
    let classesItem = examRule.questionSettingRule.find(item => item.classesCode === 'locate')
    if (classesItem) {
      classesItem.classesCode = locateClassesCode
    }
  }

  return examRule
}

/**
 *获取考试试题
 * @param options
 * @returns
 */
export const useExamQuestions = (options: any) => {
  let examType: ExamTypeEnum = parseInt(options.examType)
  let examResult: ExamResult
  let baseType: string = options.baseType
  let code: any
  let questions: LearnBaseQuestionInfo[] = []
  let examRule: ExamRule | undefined
  // 考试规则
  examRule = useExamRule(baseType)
  examResult = { examType, examReason: examRule?.examReason, baseType, driveType: examRule!.driveType, score: 0, result: 0 }

  switch (examType) {
    case ExamTypeEnum.MockExam: {
      questions = getMockExamQuestions(baseType, examRule!)
      break
    }
    case ExamTypeEnum.MockRealExam: {
      questions = getMockExamQuestions(baseType, examRule!)
      break
    }
    case ExamTypeEnum.PaperExam:
      let paperId = options.paperId
      questions = getMockExamPaperQuestions(baseType, paperId, examRule!)
      break

  }

  examResult.questions = questions.map(item => {
    let examResultQuestion: ExamResultQuestion = {
      questionId: item.questionId,
      status: -1,
      answer: ''
    }

    return examResultQuestion
  })
  return {
    questions, examRule, examResult
  }
}

/**
 * 获取考试试题
 * @param baseType
 */
const getMockExamQuestions = (baseType: string, examRule: ExamRule) => {
  let questions: LearnBaseQuestionInfo[] = []
  let randomQuestions: LearnBaseQuestionInfo[] = []
  const learnBaseInfoStore = useLearnBaseInfoStore()
  let learnBaseQuestions: LearnBaseQuestionInfo[] = learnBaseInfoStore.questions(baseType)
  let questionSettingRule = examRule?.questionSettingRule

  questionSettingRule?.forEach(questionSettingRule => {
    let classesQuestions = learnBaseQuestions.filter(item => (item.classesCode === questionSettingRule.classesCode || !questionSettingRule?.classesCode) && item.optionType == questionSettingRule.questionOptionType)
    let classesRandomQuestions = getRandomElements(classesQuestions, questionSettingRule.questionCount)
    questions = [...questions, ...classesRandomQuestions]
  })

  for (let optionType in Object.values(QuestionOptionTypeEnum)) {
    let tempOptionQuestions = questions.filter(question => question.optionType == optionType)
    let tempRandomOptionQuestions = getRandomElements(tempOptionQuestions, tempOptionQuestions.length)
    randomQuestions = [...randomQuestions, ...tempRandomOptionQuestions]
  }



  return randomQuestions;
}

/**
 * 随机读取
 * @param questions
 * @param count
 * @returns
 */
function getRandomElements(questions: LearnBaseQuestionInfo[], count: number) {
  // 创建一个新数组来存储随机选择的元素
  const result: LearnBaseQuestionInfo[] = []
  // 创建一个副本数组，以便不修改原始数组
  const array = [...questions];
  // 遍历新数组并填充随机选择的元素
  for (let i = 0; i < count; i++) {
    // 随机选择一个元素
    const randomIndex = Math.floor(Math.random() * array.length);
    // 将随机选择的元素添加到结果数组中
    result[i] = array[randomIndex];
    // 将已选择的元素从副本数组中移除
    array.splice(randomIndex, 1);
  }
  // 返回包含随机元素的新数组
  return result;
}

/**
 * 添加考试结果
 * @param examResult
 */
export const useAddExamResult = (examResult: ExamResult) => {
  const mockExamStore = useMockExamStore()
  mockExamStore.examResults.unshift(examResult)
}

/**
 * 模拟考试数据统计
 * @param baseType
 */
export const useMockExamOverView = (baseType: string) => {
  const mockExamStore = useMockExamStore()
  let examCount = 0
  let passCount = 0
  let overageScore = 0
  let errorQuestionCount = 0

  let examResults = mockExamStore.examResults.filter(item => item.baseType === baseType)
  examCount = examResults.length
  passCount = examResults.filter(item => item.result == 1).length

  let scoreCount: number = examResults.reduce((total: any, item) => {
    return total = total + item!.score!
  }, 0)

  if (scoreCount && examCount) {
    overageScore = Math.round(scoreCount / examCount)
  }

  let questions: ExamResultQuestion[] = []
  examResults.forEach(item => {
    questions = [...questions, ...item.questions!]
  })

  errorQuestionCount = questions.filter(item => item.status === 0).length
  return { examCount, passCount, overageScore, errorQuestionCount }
}

/**
 * 获取密卷试题
 * @param baseType
 * @param paperId
 * @param examRule
 */
const getMockExamPaperQuestions = (baseType: string, paperId: number, examRule: ExamRule) => {
  const learnBaseInfoStore = useLearnBaseInfoStore()
  let paperQuestionIds = learnBaseInfoStore.learnBaseInfo.preExamPapers?.find(item => item.id == paperId)?.questionIds
  let questions: LearnBaseQuestionInfo[] = learnBaseInfoStore.questions(baseType)

  questions = questions.filter((question: LearnBaseQuestionInfo) => paperQuestionIds?.includes(question.questionId!))

  let randomQuestions: LearnBaseQuestionInfo[] = []
  for (let optionType in Object.values(QuestionOptionTypeEnum)) {
    let tempOptionQuestions = questions.filter(question => question.optionType == optionType)
    // let tempRandomOptionQuestions = getRandomElements(tempOptionQuestions, tempOptionQuestions.length)
    randomQuestions = [...randomQuestions, ...tempOptionQuestions]
  }
  return randomQuestions
}


/**
 *获取考试密卷
 * @param baseType
 */
export const usePreExamPapers = (baseType: string) => {
  const learnBaseInfoStore = useLearnBaseInfoStore()
  return learnBaseInfoStore.learnBaseInfo.preExamPapers?.filter(item => item.baseTypeCode === baseType)
}
